// pages/settlement/settlement.js
var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    typeId:'',
    currentId: '', 
    consigneeName: "", 
    consigneePhone: "", 
    currentAddress: "",
    itemArry:'',
    totalPrice:'',
    totalOriPrice:'',
    orinDiscount:'',
    couponDiscount:'',
    total_fee:0.00,
    total_discount:0.00,
    goodsList:[],
    currentCouId:'',
    userCouId:'',
    money:0.1,
  },
  checkAddress() {
    wx.navigateTo({
      url: '/pages/checkAddress/checkAddress?item='+this.data.itemArry+'&addressId='+this.data.currentId+'&currentCouId='+this.data.currentCouId+'&sale=1&userCouId='+this.data.userCouId+'&typeId='+this.data.typeId,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(19950424,options.currentCouId);
    console.log(19950424,options.userCouId);
    console.log(123456,JSON.parse(options.item));
    if(options.address){
      console.log(123556,JSON.parse(options.address));
      this.setData({
        currentId: JSON.parse(options.address).currentId, 
        consigneeName: JSON.parse(options.address).consigneeName, 
        consigneePhone: JSON.parse(options.address).consigneePhone, 
        currentAddress: JSON.parse(options.address).currentAddress, 
      })
    }
    
    this.setData({
      typeId:options.typeId,
      itemArry:options.item,
      goodsList:JSON.parse(options.item).items,
      totalPrice:JSON.parse(options.item).totalPrice,
      totalOriPrice:JSON.parse(options.item).totalOriPrice,
      orinDiscount:JSON.parse(options.item).orinDiscount,
      total_discount:JSON.parse(options.item).orinDiscount,
      total_fee:0.1,
      currentCouId:options.currentCouId,
      userCouId:options.userCouId,
    })
    console.log(99123456,this.data.typeId);
  },


  generateOrderId() {
    return this.getOrderNoFunc("yyyyMMddhhmmssS")+Math.floor(Math.random() * 89) + 10; // 组合时间戳和随机数
  },
  //支付前的准备方法
  preparePay(){
    let typeId = this.data.typeId
    let _this=this;
    wx.request({
      url:app.globalData.onlineUrl+"/couponsCountByStatus",
      header:{'content-type': 'application/json'},
      method:"POST",
      data:{
        phone:wx.getStorageSync('phone'),
        discountType:typeId,
      },
      dataType:"json",
      success:function(result) {
        console.log(123123,result.data.data);
        if(result.data.data.count==0){
          wx.showToast({
            title: '券状态已经发生改变，正在跳转',
            icon: 'none',
          })
          //延迟三秒返回到券页面
          setTimeout(() => {
            wx.navigateBack({
              delta: 3,
            })
          }, 3000);
        }else{
          _this.payOrder();
        }
      }
    })
  },
  //支付
payOrder: function(event) {
  // console.log(111,event.currentTarget.dataset.type);
  let openid=wx.getStorageSync('openid')
  let phone=wx.getStorageSync('phone');
  // let dataArry=event.currentTarget.dataset.type.split(',')
  // console.log("orderId","");
  // console.log("text","测试商品");
  // console.log("total_fee","");
  // console.log("读取openid",openid);
  
  let orderId=this.generateOrderId()
  let text=orderId;
  let total_fee=this.data.money
  let _this=this
  wx.request({
    url: app.globalData.onlineUrl+'/wxpay',
    data: {
      Goods:{
        text:text,
        total_fee: total_fee*100,
      },
      openid: openid,
      orderId:orderId,
      phone:phone,
    },
    header:{'content-type': 'application/json'},
    method:"POST",
    dataType:"json",
    success: res => {
      console.log(1,res.data.data.data)
      let result=res.data.data.data
      wx.requestPayment({
        timeStamp: result.timeStamp,
        nonceStr: result.nonceStr,
        package: result.package,
        signType: result.signType,
        paySign: result.paySign,
        success: res => {
          _this.addOrder(orderId);
          _this.updateInventory();
          wx.navigateTo({
            url: '/pages/state/state?type=1'
          })
        },
        fail: res => {
          // console.log(3,res)
          // wx.navigateTo({
          //   url: '/pages/state/state?type=2'
          // })
        }
      })
    },
    complete: res => {
      
    }
  })
},
userCoupon(){
  let _this=this;
    wx.request({
      url: app.globalData.onlineUrl+'/userCoupon',
      data: {
        phone:wx.getStorageSync('phone'),
        id:_this.data.userCouId,
      },
      header:{'content-type': 'application/json'},
      method:"POST",
      dataType:"json",
      success: res => {
      }
    })
},
//处理库存
updateInventory(){
  this.data.goodsList.forEach(good => {
    // 计算新库存：原库存 - 购买数量
    const newInventory = good.inventory - good.buyNum;
    // 调用后端接口更新库存
    console.log("库存处理",newInventory);
    this.setInventory(good.productId, newInventory);
  });
},
//修改库存
setInventory(id,newInventory){
  let _this=this;
  wx.request({
    url: app.globalData.onlineUrl+'/updateInventory', 
    method: 'POST',
    data: {
      id:id,
      inventory:newInventory,
    },
    success: function(res) {
      console.log("库存处理成功");
    },
    fail: function(err) {
    },
    complete: function() {}
  });
},
  //新增订单
addOrder: function (orderId) {
  let phone=wx.getStorageSync('phone');
  let _this=this
  // const coupon =this.data.coupons.find(item => item.id === this.data.currentCouId)
  wx.request({
    url: app.globalData.onlineUrl+'/addNewOrderSuc',
    data: {
      orderId:orderId,
      phone:phone,
      totalPrice:_this.data.totalPrice,
      totalDiscount:_this.data.total_discount,
      totalFee:_this.data.money,
      couponId:_this.data.currentCouId,
      goodsJson:JSON.stringify(_this.data.goodsList),
      payTime:this.getDateNow(),
      consigneeId:_this.data.currentId?_this.data.currentId:null, 
      consigneeName:_this.data.consigneeName, 
      consigneePhone: _this.data.consigneePhone, 
      currentAddress:_this.data.currentAddress, 
      isOnlyCoupon:_this.data.isOnlyCoupon?'1':'0'
    },
    header:{'content-type': 'application/json'},
    method:"POST",
    dataType:"json",
    success: res => {
      console.log("成功")
      //使用券
      _this.userCoupon()
    }
  })
},
//获取时间
getDateNow: function(){
  const now = new Date();
  const year = now.getFullYear();
  const month = ('0' + (now.getMonth() + 1)).slice(-2);
  const day = ('0' + now.getDate()).slice(-2);
  const hours = ('0' + now.getHours()).slice(-2);
  const minutes = ('0' + now.getMinutes()).slice(-2);
  const seconds = ('0' + now.getSeconds()).slice(-2);
  return year +'-'+ month+'-'+ day +' '+ hours +':'+ minutes +':'+ seconds;
},
  getOrderNoFunc(fmt){
    let date=new Date();
    var o = {
      "M+" : date.getMonth()+1,                 //月份
      "d+" : date.getDate(),                    //日
      "h+" : date.getHours(),                   //小时
      "m+" : date.getMinutes(),                 //分
      "s+" : date.getSeconds(),                 //秒
      "q+" : Math.floor((date.getMonth()+3)/3), //季度
      "S"  : date.getMilliseconds()             //毫秒
    };
  
    if(/(y+)/.test(fmt)){
      fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
    }
          
    for(var k in o){
      if(new RegExp("("+ k +")").test(fmt)){
        fmt = fmt.replace(
          RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));  
      }       
    }
  
    return fmt;        
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})